package com.xiaojie.service;

import com.xiaojie.entity.UserAttempts;
import com.xiaojie.mapper.UserAttemptsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @ClassName LimitLoginAuthenticationProvider
 * @Description TODO
 * @Author HTGY02
 * @Date 2021/4/28 14:02
 * @Version 1.0
 **/
@Service
public class LimitLoginAuthenticationProvider extends DaoAuthenticationProvider {
    @Autowired
    private UserAttemptsMapper userAttemptsMapper;

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        super.setUserDetailsService(userDetailsService);
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        try {
            Authentication authenticate = super.authenticate(authentication);
            //如果验证通过，重置尝试次数
            userAttemptsMapper.resetFailAttempts(authentication.getName());
            return authenticate;
        } catch (AuthenticationException e) {
            //校验失败，增加校验次数
            UserAttempts userAttempts = userAttemptsMapper.selectByName(authentication.getName());
            if(userAttempts==null){
                UserAttempts attempts=new UserAttempts();
                attempts.setUsername(authentication.getName());
                userAttemptsMapper.insert(attempts);
            }else{
                if(Integer.valueOf(userAttempts.getAttempts())>=3){

                    Date lastAttempts = userAttempts.getLastModified();
                    throw new RuntimeException( "用户已经被锁定，用户名 : "
                            + authentication.getName() + "最后尝试登陆时间 : " + lastAttempts);
                }
                userAttempts.setAttempts(userAttempts.getAttempts()+1);
                userAttempts.setUsername(authentication.getName());
                userAttemptsMapper.changeRetryTimes(userAttempts);
            }
        }
        return null;
    }
}
